import axios from "@/axios"
import { loginStatus } from '@/stores/counter'

import { jwtDecode } from 'jwt-decode';
// 扩展接口
interface JwtPayload {
    id: string;
}

async function getUserById(id: string): Promise<any> {
    try {
        const response = await axios.get(`/users/${id}`,);
        return response.data;

    } catch (error) {
        console.error('getUserById', error);
        throw error;
    }
}


export async function relogin(): Promise<void> {
    const login_status = loginStatus();
    console.log("try relogin: ");
    try {
        // 读取 token
        const token = localStorage.getItem("token");
        if (!token) {
            return;
        }
        // 解析 token
        const parsedToken: JwtPayload = jwtDecode(token)
        console.log(parsedToken);
        // 获取用户信息
        const userInfo = await getUserById(parsedToken.id)
        // 登录
        login_status.login({ id: parsedToken.id, ...userInfo }, false);
        return;
    } catch (error) {
        // 处理登录失败的情况
        login_status.logout();
        setTimeout(() => { window.$utils.message.error('登录信息错误：' + error); }, 1000);
        console.error('Login error:', error);
        throw error; // 将错误抛出，以便在调用时可以捕获
    }
}
